/*
 * 
 * Copyright 2011 visual-analysis-of-cancer.
 * This file is part of visual-analysis-of-cancer.
 * 
 * visual-analysis-of-cancer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * visual-analysis-of-cancer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with kOSMik.  If not, see <http://www.gnu.org/licenses/>.
 *  
 * visual-analysis-of-cancer:
 * An tool to analye the WHO and GLOBOCAN cancer data.
 * http://code.google.com/p/visual-analysis-of-cancer/
 * 
 * 
 * 
 * Authors: Erik Sniegula, Johannes Dahlke
 * 
 * Module:  Programming in Processing for Visual Analytics
 * Group:   20
 * 
 * Created: Aug. 2011
 * Version: 1.0
 *
 */
 




package de.fuberlin.processing.who.cancer.gui;

import java.util.Collection;
import java.util.Observable;
import java.util.Observer;
import processing.core.PApplet;
//import sun.awt.X11.Screen;
import controlP5.ControlCanvas;
import controlP5.ControlGroup;
import controlP5.ControlP5;
import controlP5.Controller;
import controlP5.ControllerDisplay;
import controlP5.Tab;
import de.fuberlin.processing.who.cancer.controlp5ex.CustomTooltip;
import de.fuberlin.processing.who.cancer.data.DBException;
import de.fuberlin.processing.who.cancer.data.Database;
import de.fuberlin.processing.who.cancer.data.DatabaseConnector;
import de.fuberlin.processing.who.cancer.gui.healthgraph.CancerDisc;
import de.fuberlin.processing.who.cancer.gui.healthgraph.OrbitalSystemImpl;
import de.fuberlin.processing.who.cancer.interaction.CancerCauses;
import de.fuberlin.processing.who.cancer.interaction.CausesBroadcaster;
import de.fuberlin.processing.who.cancer.interaction.LocationBroadcaster;
import de.fuberlin.processing.who.cancer.interaction.LocationModifier;
import de.fuberlin.processing.who.cancer.run.CancerSketch;
import de.fuberlin.processing.who.cancer.utils.Notification;


public class HealthGraph extends Controller implements Observer {

	public static final int NUM_GRAPH_WIDTH = CancerSketch.NUM_SKETCH_WIDTH
			- Scatterplot.NUM_PLOT_WIDTH - 3* CancerSketch.NUM_SKETCH_PADDING;
	public static final int NUM_GRAPH_HEIGHT = CancerSketch.NUM_SKETCH_HEIGHT
			- CancerSketch.NUM_SKETCH_PADDING - ParameterMenu.NUM_LIST_HEIGHT;
	
	public static final int NUM_SCALE_MARGIN = 20;
	public static final int NUM_SCALE_TITLE_MARGIN = 15;
	
	private int left;
	private int top;
	private LocationModifier locationModifier;
	private DatabaseConnector db;
	private OrbitalSystemImpl orbitalSystem;
	private ControlGroup controlGroup;
	private Float maxHealthFinancing;
	private Integer maxLifeExpectancy;
	private int canvasColor;
//	private CustomTooltip tooltipSystem;


	public HealthGraph( ControlP5 theControlP5, String theName, int theX, int theY) {
		super( theControlP5, (Tab) ( theControlP5.getTab( "default")), theName,
				theX, theY, NUM_GRAPH_WIDTH, NUM_GRAPH_HEIGHT);
		this.left = theX;
		this.top = theY;
		int margin = Math.max( (int) CancerDisc.NUM_MIN_CIRCLE_RADIUS, NUM_SCALE_MARGIN);

		if ( !( controlP5.getTooltip() instanceof CustomTooltip)) {
			Notification
					.printErrorMessage( "Wrong Tooltip: Expect an instance of CustumTooltip.");
		} else {
			// we want to be informed about changes of location
			this.locationModifier = LocationBroadcaster.get();
			this.locationModifier.addObserver( this);
			// We want to know the cause, which we have to visualize
			CausesBroadcaster.get().addObserver( this);

			initThisControl();
			
			orbitalSystem = new OrbitalSystemImpl( margin, margin, controlGroup.getWidth()
					- ( 2 * margin), controlGroup.getHeight() - ( 2 * margin),
					(CustomTooltip) controlP5.getTooltip());
			connectToDatabase();
			preloadData();

			this.getCaptionLabel().setVisible( false);
		}
	}


	private void initThisControl() {
		controlGroup = controlP5.addGroup( "healthGraphControlGroup", left+NUM_SCALE_TITLE_MARGIN, top+NUM_SCALE_TITLE_MARGIN,
				width -2*NUM_SCALE_TITLE_MARGIN);
		controlGroup.hideBar();
		controlGroup.setHeight( height -2*NUM_SCALE_TITLE_MARGIN);
		this.canvasColor = controlP5.papplet.color( 0, 54, 82);
		
		// controlGroup.setBackgroundHeight( height);
		controlGroup.addCanvas( new ControlCanvas() {
			
			@Override
			public void draw( PApplet theApplet) {
				theApplet.fill( canvasColor); 
				theApplet.rect( 0, 0, width -2*NUM_SCALE_TITLE_MARGIN, height -2*NUM_SCALE_TITLE_MARGIN);
			}
		});
	}


	private void connectToDatabase() {
		try {
			db = Database.get();
		} catch ( DBException e) {
			e.printStackTrace();
		}
	}


	private void preloadData() {
		// dataLifeExpectancyByHealthFinancing =
		// db.getLifeExpectancyByHealthFinancing();
		maxHealthFinancing = db.getMaxHealthFinancing();
		maxLifeExpectancy = db.getMaxLifeExpenctancy();
	}


	// overwrite the draw method for the controller's visual representation.
	public void draw( PApplet p) {
		p.pushStyle();
		p.stroke( canvasColor);
		p.strokeWeight( 2);
		p.fill( 255);
    p.rect( this.position.x,  this.position.y, width, height);
    
    // Title Health Financing
    String textHealthFinancing = "Health Financing (total expenditures per GDP)";
    float offset = p.textWidth( textHealthFinancing) / 2.0f;
    p.textSize( 10);
    p.fill( canvasColor);
    p.text( textHealthFinancing, this.position.x + (width /2) -offset, this.position.y + 12);
    p.text( textHealthFinancing, this.position.x + (width /2) -offset, this.position.y + height -4);
    
    // Title Life Expectancy
    String textLifeExpectancy = "Life Expectancy (years)";
    offset = p.textWidth( textLifeExpectancy) / 2.0f;
    p.pushMatrix();
    p.translate( this.position.x + (width /2), this.position.y + (height /2));
    p.rotate( - PI /2);
    p.text( textLifeExpectancy, -offset, 11 -(width /2));
    p.text( textLifeExpectancy, -offset, (width /2) -4);
    p.popMatrix();
    p.popStyle();
	}


	@Override
	public Controller setValue( float theValue) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public void update( Observable observable, Object arg) {
		if ( observable instanceof LocationBroadcaster) {
			locationModifier.getLocations();
			Collection<Integer> selectedLocations = locationModifier.getLocations();
			updateLocations( selectedLocations);
		} else if ( observable instanceof CausesBroadcaster) {
			CancerCauses cancerCause = (CancerCauses) arg;
			updateCancerCause( cancerCause);
		}
	}


	private void updateLocations( final Collection<Integer> selectedLocations) {
		orbitalSystem.clear();
		CancerDisc.resetRadiusScaleFactor();
		
		for ( Integer location : selectedLocations) {
			orbitalSystem.registerOrbit( new CancerDisc( controlP5, controlGroup,
					location));
		}

		/*Thread cancerDiscsInsertThread = new Thread( new Runnable() {

			public void run() {
				ProgressMonitor progressMonitor = new ProgressMonitor(
						ControlP5.papplet, "Message", "Note", 0, selectedLocations.size());
				progressMonitor.setMillisToPopup( 0);
				
				int alreadyInsertedCancerDiscs = 0;
				for ( Integer location : selectedLocations) {
					progressMonitor.setProgress( ++alreadyInsertedCancerDiscs);
					orbitalSystem.registerOrbit( new CancerDisc( controlP5, controlGroup,
							location));
				}
				try {
					Thread.sleep( 100);
				} catch ( Exception ex) {
				}
			}
		});
		try {
			SwingUtilities.invokeAndWait( cancerDiscsInsertThread);
		} catch ( InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch ( InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} */

	}
	
	
	@Override
	protected void mousePressed() {
		//this.width = controlP5.papplet.width;
		//this.controlGroup.setWidth( controlP5.papplet.width);
		//orbitalSystem.doUpdate();
		super.mousePressed();
	}
	
	private void updateCancerCause( CancerCauses cancerCause) {
		CancerDisc.setCancerCause( cancerCause);
		orbitalSystem.doUpdate();
	}

	
}
